<template>
<!-- 登录对话框 -->
  <a-modal 
    v-model:open="userStore.isLoginModalVisible" 
    :width="640"
    centered
    :footer="null"
    :closable="false"
  >
    <div class="modal-header">
      <h2>CApi</h2>
      <p class="sub-title">开发者接口开放平台</p>
    </div>
    
    <a-form ref="loginFormRef" :model="loginForm" layout="horizontal" class="login-form">
      <a-form-item 
        name="userAccount"
        :rules="[
          { required: true, message: '请输入账号' },
          { min: 4, message: '账号长度需大于4位' },
          { max: 32, message: '账号长度需小于32位' }
        ]"
      >
        <a-input 
          v-model:value="loginForm.userAccount" 
          placeholder="请输入账号"
          size="large"
          class="custom-input"
        >
          <template #prefix>
            <user-outlined class="input-icon" />
          </template>
        </a-input>
      </a-form-item>
      
      <a-form-item 
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度需大于8位' },
          { max: 32, message: '密码长度需小于32位' }
        ]"
      >
        <a-input-password 
          v-model:value="loginForm.userPassword" 
          placeholder="请输入密码"
          size="large"
          class="custom-input"
        >
          <template #prefix>
            <lock-outlined class="input-icon" />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 24 }">
        <a-button 
          type="primary" 
          block 
          size="large"
          @click="handleLogin"
          :loading="loginLoading"
        >
          立即登录
        </a-button>
      </a-form-item>

      <div class="form-footer">
        <a href="#" @click.prevent="showRegister">注册账号</a>
      </div>
    </a-form>
  </a-modal>

  
<!-- 注册对话框 -->
<a-modal 
  v-model:open="registerVisible" 
  :width="640"
  centered
  :footer="null"
  :closable="false"
>
  <div class="modal-header">
    <h2>用户注册</h2>
    <p class="sub-title">加入CApi开发者平台</p>
  </div>
  
  <a-form :model="registerForm" layout="horizontal" class="login-form">
    <a-form-item 
      name="userAccount"
      :rules="[
        { required: true, message: '请输入注册账号' },
        { min: 4, message: '账号长度需4-32位' },
        { max: 32, message: '账号长度需4-32位' }
      ]"
    >
      <a-input 
        v-model:value="registerForm.userAccount" 
        placeholder="请输入账号"
        size="large"
        class="custom-input"
      >
        <template #prefix>
          <user-outlined class="input-icon" />
        </template>
      </a-input>
    </a-form-item>

    <a-form-item 
      name="userPassword"
      :rules="[
        { required: true, message: '请输入8-32位密码' },
        { min: 8, message: '密码长度需8-32位' },
        { max: 32, message: '密码长度需8-32位' }
      ]"
    >
      <a-input-password 
        v-model:value="registerForm.userPassword" 
        placeholder="请输入密码"
        size="large"
      >
        <template #prefix>
          <lock-outlined class="input-icon" />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item 
      name="checkPassword"
      :rules="[{ required: true, message: '请再次输入密码' }]"
    >
      <a-input-password 
        v-model:value="registerForm.checkPassword" 
        placeholder="请确认密码"
        size="large"
      >
        <template #prefix>
          <lock-outlined class="input-icon" />
        </template>
      </a-input-password>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 24 }">
      <a-button 
        type="primary" 
        block 
        size="large"
        @click="handleRegister"
        :loading="registerLoading"
      >
        立即注册
      </a-button>
    </a-form-item>
  </a-form>
</a-modal>


  <!-- 主体内容 -->
  <a-space direction="vertical" :style="{ width: '100%' }" :size="[0, 48]">
    <a-layout>
      <a-layout-header class="header" theme="light">
        <a-flex justify="space-between">
          <div style="width: 10vw;">
            <router-link to="/"><h1 style="line-height: initial">CApi</h1></router-link>
          </div>
          <div style="flex: 1; min-width: 0; padding: 0 20px;">
            <a-menu
              v-model:selectedKeys="selectedKeys"
              theme="light"
              mode="horizontal"
              :style="{ 
                lineHeight: '64px',
                flexWrap: 'nowrap',
                whiteSpace: 'nowrap',
                overflow: 'visible'
              }"
            >
              <a-menu-item 
                key="home" 
                :style="{ flexShrink: 0, padding: '0 16px' }"
              ><router-link to="/home">首页</router-link></a-menu-item>
              <a-menu-item 
                key="market" 
                :style="{ flexShrink: 0, padding: '0 16px' }"
              ><router-link to="/market">Api市场</router-link></a-menu-item>
              <a-menu-item 
                key="console" 
                :style="{ flexShrink: 0, padding: '0 16px' }"
              ><router-link to="/console">控制台</router-link></a-menu-item>
              <a-menu-item 
                key="manage" 
                v-if="userStore.user?.userRole === 'admin'"
                :style="{ flexShrink: 0, padding: '0 16px' }"
              ><router-link to="/manage">管理</router-link></a-menu-item>
            </a-menu>
          </div>
        
          <div style="width: 10vw; text-align: right;">
            <template v-if="userStore.isLoggedIn">
              <a-dropdown>
                <a-button type="link" style="padding: 0 15px;">
                  <a-avatar :src="userStore.user?.userAvatar" style="background-color: #1890ff">
                  </a-avatar>
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="profile">
                      <a href="javascript:;" @click="handleProfile">个人中心</a>
                    </a-menu-item>
                    <a-menu-item key="logout">
                      <a href="javascript:;" @click="logout">退出登录</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </template>
            <template v-else>
              <a-button type="primary" @click="userStore.showLoginModal">登录</a-button>
            </template>
          </div>
        </a-flex>

      </a-layout-header>


      <a-layout-content class="content">
        <router-view></router-view>
      </a-layout-content>


    
      <a-layout-footer class="footer"><FooterCom></FooterCom></a-layout-footer>
    </a-layout>
  </a-space>
</template>


<script lang="ts" setup>
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
import { UserControllerService } from './openapi/api'; // 添加API导入
import { message } from 'ant-design-vue';
import { ref, watchEffect, onMounted } from 'vue';
import FooterCom from "./components/FooterCom.vue";
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import { useUserStore } from './stores/userStore';

const selectedKeys = ref(['1']);
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

function updateSelectedKeys() {
  selectedKeys.value = [route.path.split('/')[1]];
}
watchEffect(updateSelectedKeys);

const loginForm = ref({
  userAccount: '',
  userPassword: ''
});


const loginLoading = ref(false);

// 登录
// 在脚本部分修改登录处理函数
const loginFormRef = ref();

const handleLogin = async () => {
  try {
    // 先进行表单验证
    loginLoading.value = true;
    if (loginFormRef.value === null) {
      message.error('请输入账号密码');
      loginLoading.value = false;
      return;
    }
    if (loginForm.value.userAccount.length < 4 || loginForm.value.userAccount.length > 32) {
      message.error('账号长度需4-32位');
      loginLoading.value = false;
      return;
    }
    if (loginForm.value.userPassword.length < 8 || loginForm.value.userPassword.length > 32) {
      message.error('密码长度需8-32位');
      loginLoading.value = false;
      return;
    }
    
    // 原有登录逻辑保持不变
    const response = await UserControllerService.userLoginUsingPost({
      userLoginRequest: loginForm.value
    });
      if (response.data && response.code === 200) {
        userStore.isInitialized = true;
        userStore.isLoggedIn = true;
        userStore.user = response.data;
        userStore.hideLoginModal();
        message.success('登录成功');
      }
    } catch (error) {
      message.error(error.response.data.message || '登录失败');
    }
    finally{
      loginLoading.value = false;
    }
};

// 退出登录
const logout = async () => {
  try {
    await UserControllerService.userLogoutUsingPost();
    userStore.isLoggedIn = false;
    userStore.isInitialized = false;
    userStore.user = {};
    message.success('已退出登录');
  } catch (error) {
    message.error('退出登录失败');
  }
};

// 注册跳转方法
const registerVisible = ref(false);
const registerLoading = ref(false);
const registerForm = ref({
  userAccount: '',
  userPassword: '',
  checkPassword: ''
});

const showRegister = () => {
  registerVisible.value = true;
};

const handleRegister = async () => {
  registerLoading.value = true;
  try {
    if (registerForm.value.userPassword !== registerForm.value.checkPassword) {
      message.error('两次输入的密码不一致');
      return;
    }
    if (registerForm.value.userAccount.length < 4 || registerForm.value.userAccount.length > 32) {
      message.error('账号长度需4-32位');
      return;
    }
    if (registerForm.value.userPassword.length < 8 || registerForm.value.userPassword.length > 32) {
      message.error('密码长度需8-32位');
      return;
    }
    
    const response = await UserControllerService.userRegisterUsingPost({
      userRegisterRequest: {
        userAccount: registerForm.value.userAccount,
        userPassword: registerForm.value.userPassword,
        checkPassword: registerForm.value.checkPassword
      }
    });

    if (response.code === 200) {
      message.success('注册成功');
      registerVisible.value = false;
    }

  } catch (error) {
    console.error('注册请求失败', error);
    message.error(error.response.data.message || '注册失败');
  } finally {
    registerLoading.value = false;
  }
};

// 添加路由守卫
router.beforeEach(async(to) => {
  if(userStore.isInitialized === false){
    await userStore.checkLoginStatus();
  }
  if(userStore.isLoggedIn === false && to.path !== '/home'){
    message.error('请先登录');
    router.push('/home');
    return false;
  }
  if (to.path.startsWith('/manage')) {
    if (userStore.user?.userRole !== 'admin') {
      message.error('权限不足');
      router.push('/home');
      return false;
    }
  }
});

// 个人中心跳转
const handleProfile = () => {
  router.push('/profile');
};

</script>

<style scoped>
/* 新增头像悬停效果 */
.ant-avatar {
  cursor: pointer;
  transition: all 0.3s;
  &:hover {
    box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
  }
}

/* 调整下拉菜单样式 */
.ant-dropdown-menu {
  min-width: 120px;
  a {
    color: rgba(0, 0, 0, 0.85);
    &:hover {
      color: #1890ff;
    }
  }
}

.header{
  text-align: center;
  color: #108ee9;
  height: 64px;
  padding-inline: 50px;
  line-height: 64px;
  background-color: #ffffff;
}

.content{
  text-align: center;
  color: #0a1115;
  min-height: 100vh;
}

.footer{
  text-align: center;
  color: #7dbcea;
  background-color: #fff;
}


.form-footer {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: right;
  align-items: center;
}

/* 新增模态框头部样式 */
.modal-header {
  text-align: center;
  padding: 24px 0 16px;
  
  h2 {
    font-size: 28px;
    color: #1890ff;
    margin-bottom: 8px;
  }
  
  .sub-title {
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
  }
}


.input-icon {
  color: rgba(0, 0, 0, 0.25) !important;
  margin-right: 8px;
}

/* 优化登录按钮 */
.login-form :deep(.ant-btn-primary) {
  background: linear-gradient(90deg, #1890ff, #69b1ff);
  width: 60%;
  display: block;
  margin: 12px auto 0;
  transition: all 0.3s;
  &:hover {
    opacity: 0.8;
  }
}

/* 优化表单容器 */
.login-form {
  padding: 0 60px 24px;
  max-width: 520px;
  margin: 0 auto;
}

/* 调整表单项对齐 */
.login-form :deep(.ant-form-item-label) {
  text-align: left;
  padding-right: 12px;
}

.login-form :deep(.ant-form-item-control) {
  flex: 1;
}

/* 调整表单项间距 */
.login-form :deep(.ant-form-item) {
  margin-bottom: 20px;
}

</style>

